﻿function UpdateUI(Result)
{
    InitializeJobPanel(Result);

    UpdatePanel(Result);

    UpdateInstancesTable(Result.InstanceResults);

    UpdateChart(Result.ChartSeries);
}

function InitializeJobPanel(Result)
{
    if (typeof chart == "undefined")
    {
        document.getElementById('h2Title').innerHTML = Result.JobName;
        document.getElementById('Duration').innerHTML = Result.Duration;
        document.getElementById('servicehref').innerHTML = Result.ServiceName;
        document.getElementById('servicehref').href = Result.ServiceName;
    }
}


function SetUIFinished()
{
    document.getElementById('progressbar').style.display = 'none';
    document.getElementById('progressComponentsDiv').style.visibility = 'hidden';
    document.getElementById('EndedDiv').style.visibility = 'visible';

    ShowHideChartElements(true);
}

function UpdatePanel(panelData)
{
    document.getElementById("progressbarLeft").style.width = panelData.Progress + "%";
    document.getElementById("progressbarRight").style.width = (100-panelData.Progress) + "%";
    document.getElementById("StartedDateTime").innerHTML = panelData.StartedDateTime;
    document.getElementById("EndedDateTime").innerHTML = panelData.EndedDateTime;
    document.getElementById("Remaining").innerHTML = panelData.RemainingTime;
    document.getElementById("progressValue").innerHTML = panelData.Progress + "%";


    var panelHtml = "" +
        "<div class=\"span3 bg-color-blueLight\">" +
            "<h3>&nbsp;Requests</h3>" +
            "<h4>&nbsp;" + panelData.TotalCount + "</h4>" +
        "</div>" +
        "<div class=\"span3 bg-color-blueLight\">" +
            "<h3>&nbsp;Last Average</h3>" +
            "<h4>&nbsp;" + panelData.LastAvgResponseTime + "&nbsp;ms</h4>" +
        "</div>" +
            "<div class=\"span3 bg-color-blueLight\">" +
            "<h3>&nbsp;Max</h3>" +
            "<h4>&nbsp;" + panelData.MaxResponseTime + "&nbsp;ms</h4>" +
        "</div>" +
        "<div class=\"span3 bg-color-blueLight\">" +
            "<h3>&nbsp;Errors</h3>" +
            "<h4>&nbsp;" + panelData.Errors + "</h4>" +
        "</div>";

    $("#panel").html(panelHtml);
}

function UpdateInstancesTable(TableData)
{
    InstancesTable.fnClearTable(false);

    var arrayOfThisRow = [];
    for (i = 0; i < TableData.length; i++)
    {
        var item = TableData[i];
        arrayOfThisRow[i] = new Array(item.InstanceName, item.Count, item.LastAvgResponseTime, item.Errors, item.AvgThreadCount);
    }

    InstancesTable.fnAddData(arrayOfThisRow, true);
}


function UpdateChart(Series)
{   
    if (typeof chart == "undefined")
    {
        InitializeChart(Series);
    }
    else
    {          
        AddSeriesToChart(Series);
    }
}

var chart;
var ChartCounter;
function InitializeChart(Series)
{
    ChartCounter = 0;
    console.log("ChartCounter: " + ChartCounter);

    var responseSeries = [];
    var threadSeries = [];
    var errorSeries = [];

    for (var i = 0; i < Series.length; i++)
    {
        var dateArr = Series[i][0].split(";");
        var dateTimeObject = new Date(Date.UTC(dateArr[0], dateArr[1] - 1, dateArr[2], dateArr[3], dateArr[4], dateArr[5], dateArr[6]));
        var x = dateTimeObject.getTime();

        var yParts = Series[i][1].split(";");
        var yResponse = parseInt(yParts[0]);
        var yThreads = parseInt(yParts[1]);
        var yErrors = parseInt(yParts[2]);

        responseSeries.push([x, yResponse]);
        threadSeries.push([x, yThreads]);
        errorSeries.push([x, yErrors]);

        ChartCounter++;
    }

   
    chart = new Highcharts.StockChart({
        chart:
            {
                plotBorderWidth: 1,
                renderTo: 'chartContainer',
                events: {
                    load: function ()
                    {
                        console.log("chart loaded");
                    }           
                },
            },
        rangeSelector: {
            buttons: [{
                count: 1,
                type: 'minute',
                text: '1M'
            }, {
                count: 5,
                type: 'minute',
                text: '5M'
            }, {
                count: 15,
                type: 'minute',
                text: '15M'
            },{
                count: 30,
                type: 'minute',
                text: '30M'
            },{
                type: 'all',
                text: 'All'
            }],
            inputEnabled: false,
            selected: 4
        },
        legend: {
            enabled: true,
            itemHiddenStyle: {
                color: '#333'
            }
        },
        exporting: {
            enabled: false
        },
        xAxis: {
            lineColor: '#000',
            gridLineWidth: 1
        },
        yAxis: [{ // Primary yAxis
            gridLineWidth: 1,
            labels: {
                align: 'right',
                x: -10,
                formatter: function() {
                    return this.value +'ms';
                }
            },
            title: {
                text: 'AvgResponseTime'
            },

            lineColor: '#000',
            lineWidth: 1,
            min: 0,
            showEmpty: false
        }, { // Secondary yAxis
            gridLineWidth: 1,
            labels: {
                align: 'left',
                x: +10,
            },
            title: {
                text: 'ActiveThreads'
            },

            lineColor: '#000',
            lineWidth: 1,
            min: 0,
            minTickInterval: 5,
            opposite: true,
            showEmpty: false
        }, { // Tertiary yAxis
            gridLineWidth: 1,
            labels: {
                align: 'left',
                x: +10,
            },
            title: {
                text: 'Errors'
            },

            lineColor: '#000',
            lineWidth: 1,
            min: 0,
            opposite: true,
            showEmpty: false
        }],
        tooltip: {
            shared: true
        },
        tooltip: {
            formatter: function ()
            {
                var d = new Date(this.x);
 
                var tooltip = "<span style=\"font-size: 10px\">" + Highcharts.dateFormat('%d %b %Y, %H:%M:%S', this.x) + "</span><br/>";
                for (i = 0; i < this.points.length; i++)
                {
                    if (this.points[i].series._i == 0) {
                        tooltip += "<span style=\"color:" + this.points[i].series.color + "\">" + this.points[i].series.name + "</span>: <b>" + Math.round(this.points[i].y) + " ms" + "</b><br/>";
                    }
                    else
                    {
                        tooltip += "<span style=\"color:" + this.points[i].series.color + "\">" + this.points[i].series.name + "</span>: <b>" + Math.round(this.points[i].y) + "</b><br/>";
                    }
                }

                return tooltip;
            },
            style:
                {
                    margin: 10
                }
        },
        plotOptions: {
            series:
                [{
                    turboThreshold: 0
                }],
            line:
                {
                    turboThreshold: 0,
                    events: {
                        legendItemClick: function ()
                        {
                            return false; 
                        }
                    }
                }
        },
        series: [{
            name: 'AvgResponseTime',
            color: '#2D89EF',
            type: 'line',           
            data: responseSeries,
            dataGrouping:
            {
                approximation: "average",
                smoothed: true,
                groupPixelWidth: 5,
                units: [[
                    'millisecond',
                    [1, 2, 5, 10, 20, 25, 50, 100, 200, 500]
                ], [
                    'second',
                    [1, 2, 5, 10, 15, 30]
                ], [
                    'minute',
                    [1]
                ]]
            },  
        }, {
            name: 'ActiveThreads',
            type: 'line',
            color: '#00A300',
            yAxis: 1,
            dashStyle: 'shortdot',
            data: threadSeries,
            dataGrouping:
            {
                approximation: "average",
                smoothed: true,
                groupPixelWidth: 5,
                units: [[
                    'millisecond',
                    [1, 2, 5, 10, 20, 25, 50, 100, 200, 500]
                ], [
                    'second',
                    [1, 2, 5, 10, 15, 30]
                ], [
                    'minute',
                    [1]
                ]]
            }    
        }, {
            name: 'Errors',
            data: errorSeries,
            color: '#EE1111',
            type: 'line',
            yAxis: 2,           
            dashStyle: 'shortdash',
            dataGrouping:
            {
                approximation: "average",
                smoothed: true,
                groupPixelWidth: 5,
                units: [[
                    'millisecond',
                    [1, 2, 5, 10, 20, 25, 50, 100, 200, 500]
                ], [
                    'second',
                    [1, 2, 5, 10, 15, 30]
                ], [
                    'minute',
                    [1]
                ]]
            }
            
        }]
    });

    ShowHideChartElements(false)
}


function AddSeriesToChart(Series)
{
    for (var i = 0; i < Series.length; i++)
    {
        var dateArr = Series[i][0].split(";");
        var dateTimeObject = new Date(Date.UTC(dateArr[0], dateArr[1] - 1, dateArr[2], dateArr[3], dateArr[4], dateArr[5], dateArr[6]));
        var x = dateTimeObject.getTime();

        var yParts = Series[i][1].split(";");
        var yResponse = parseInt(yParts[0]);
        var yThreads = parseInt(yParts[1]);
        var yErrors = parseInt(yParts[2]);

        chart.series[0].addPoint([x, yResponse], false, false);
        chart.series[1].addPoint([x, yThreads], false, false);
        chart.series[2].addPoint([x, yErrors], false, false);
        

        ChartCounter++;       
    }


    chart.redraw();   
}

function ShowHideChartElements(show)
{
    if (show) {
        ////RangeSelector
        chart.rangeSelector.zoomText.show();
        $.each(chart.rangeSelector.buttons, function () {
            this.show();
        });
        $(chart.rangeSelector.divRelative).show();

        //Navigator and Scrollbar
        chart.scroller.scrollbar.show();
        chart.scroller.scrollbarGroup.show();
        chart.scroller.xAxis.labelGroup.show();
        chart.scroller.xAxis.gridGroup.show();
        chart.scroller.series.show();
        chart.scroller.navigatorGroup.show();       
        $.each(chart.scroller.elementsToDestroy, function (i, elem) {
            elem.show();
        })
    }
    else {
        //RangeSelector
        chart.rangeSelector.zoomText.hide();
        $.each(chart.rangeSelector.buttons, function () {
            this.hide();
        });
        $(chart.rangeSelector.divRelative).hide();

        //Navigator and Scrollbar
        chart.scroller.scrollbar.hide();
        chart.scroller.scrollbarGroup.hide();
        chart.scroller.xAxis.labelGroup.hide();
        chart.scroller.xAxis.gridGroup.hide();
        chart.scroller.series.hide();
        chart.scroller.navigatorGroup.hide();
        $.each(chart.scroller.elementsToDestroy, function (i, elem) {
            elem.hide();
        })
    }
}